<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\QrCodeController;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户微信信息
 * Class ArticleTypeModel
 * @package app\common\model
 */
class UserInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    public $table = 'user_info';


    /*关联微信账号*/
    public function conWechat()
    {
        return $this->hasOne(UserWechatInfo::class, 'id', 'wechat_id');
    }


    /*关联图书馆账号*/
    public function conLibrary()
    {
        return $this->hasOne(UserLibraryInfo::class, 'id', 'account_id');
    }

    /*关联用户预约申请记录*/
    public function conReservation()
    {
        return $this->hasMany(ReservationApply::class, 'user_id', 'id');
    }
    /**
     * 获取一个默认头像
     */
    public function getDefaultHeadImg()
    {
        $controllerObj = new Controller();
        return $controllerObj->getImgAddrUrl() . 'default/default_head_img.png';
    }
    /**
     * 根据用户id  获取微信信息
     * $param field
     */
    public static function getWechatField($user_id, $field)
    {
        $wechat_id = self::where('id', $user_id)->value('wechat_id');
        $res = UserWechatInfo::select($field)->where('id', $wechat_id)->first();
        if (is_string($field)) {
            return $res[$field];
        }
        return $res;
    }

    /**
     * 根据用户id  获取微信信息
     * $param field
     */
    public function getUserInfoByWechatId($wechat_id, $field = null)
    {
        $res = $this->where('wechat_id', $wechat_id)->first();
        if ($res && $field && !empty($res[$field])) {
            return $res[$field];
        }
        return $res;
    }


    /**
     * 判断用户是否存在
     * @param user_guid 用户guid
     */
    public function getUserInfo($user_guid)
    {
        $res = $this->where('token', $user_guid)->first();
        if (empty($res)) {
            return false;
        }

        return $res;
    }

    /**
     * 根据用户id，获取微信信息
     * @param user_guid 用户guid
     */
    public function getWechatInfo($user_guid)
    {
        $wechat_id = $this->where('token', $user_guid)->value('wechat_id');
        if (empty($wechat_id)) {
            return false;
        }
        $wechat_info = UserWechatInfo::select('nickname', 'head_img', 'tel', 'open_id')->where('id', $wechat_id)->first();
        return $wechat_info ? $wechat_info->toArray() : null;
    }
    /**
     * 根据用户id，获取读者证号信息
     * @param user_guid 用户guid
     */
    public function getAccountInfo($user_guid)
    {
        $account_id = $this->where('token', $user_guid)->value('account_id');
        if (empty($account_id)) {
            return false;
        }

        $account_info = UserLibraryInfo::select('account')->where('id', $account_id)->first();
        return $account_info ? $account_info->toArray() : null;
    }

    /**
     * 获取用户guid  根据关键字
     * @param keywords  微信昵称检索
     */
    public function getUserGuidByKeywords($keywords)
    {
        $wechat_id = UserWechatInfo::where('nickname', 'like', $keywords . '%')->value('id');
        if (empty($wechat_id)) {
            return false;
        }
        $user_guid = $this->where('wechat_id', $wechat_id)->value('token');
        return $user_guid;
    }



    /**关联书籍信息 */
    public function conBookRead()
    {
        return $this->hasMany(AudioBookRead::class, 'user_id', 'id');
    }

    /**
     * 根据user_id 获取读者证号id
     */
    public function getAccountId($user_id)
    {
        $account_id = $this->where('id', $user_id)->value('account_id');
        if (empty($account_id)) {
            return false; //未绑定
        }
        return $account_id;
    }
    /**
     * 根据account_id 获取用户id
     */
    public function getUserIdByAccount($account_id)
    {
        $id = $this->where('account_id', $account_id)->value('id');
        if (empty($id)) {
            return false; //未绑定
        }
        return $id;
    }


    /**
     * 读者证号绑定在用户信息上
     */
    public function setAccountBindUserInfo($account_id, $wechat_id = null)
    {
        $user_info = $this->where('account_id', $account_id)->first();

        if (empty($user_info)) {
            $this->account_id = $account_id;
            $this->token = get_guid();

            $qrCodeObj = new QrCodeController();
            $qr_code = $qrCodeObj->getQrCode('user_info');

            $this->qr_code = $qr_code;
            $this->qr_url = $qrCodeObj->setQr($qr_code, true);

            if ($wechat_id)  $this->wechat_id = $wechat_id;

            $this->save();
            $token = $this->token;
            $id = $this->id;
        } else {
            if ($wechat_id && $user_info->wechat_id != $wechat_id) {
                $user_info->wechat_id = $wechat_id;
                $user_info->save();
            }

            $token = $user_info->token;
            $id = $user_info->id;
        }

        return ['token' => $token, 'id' => $id];
    }

    /**
     * 用户列表
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     * @param keywords_type 关键词类型  1 读者证号 2 读者证号名字 3身份证号码 4电话号码 5微信昵称
     * @param is_volunteer 是否是志愿者 0全部  1 是  2 否
     * @param is_violate 是否违规 0全部  1 是  2 否
     * @param sort 排序方式   1 默认排序（默认）  2 积分倒序   3 邀请数量排序
     */
    public function lists($keywords, $keywords_type, $is_volunteer, $is_violate, $sort = 1, $limit = 10)
    {
        // $userViolateModel = new UserViolate();
        // $violate_config = config("other.violate_config");
        // if ($violate_config) {
        //     $violate_config_field = array_column($violate_config, 'field');
        //     $userViolateModel->resetViolate('', $violate_config_field); //重置一次查询数据
        // }

        if ($sort == 2) {
            $sort = 'score';
        } elseif ($sort == 3) {
            $sort = 'invite_number';
        } else {
            $sort = 'create_time';
        }

        $violate_config = config("other.violate_config");
        $field = [
            'u.id',
            'u.id as user_id',
            'u.account_id',
            'u.wechat_id',
            'l.account',
            'l.username',
            'l.sex',
            'l.id_card',
            'l.tel',
            'l.score',
            'u.create_time',
            'u.is_volunteer',
            'w.nickname',
            'w.head_img'
        ];
        //动态返回数据
        foreach ($violate_config as $key => $val) {
            $field[] = $val['field'] . '_violate_num';
        }
        //    DB::enableQueryLog();
        $res = $this->from('user_info as u')
            ->select($field)
            ->leftjoin('user_account_lib as l', 'l.id', '=', 'u.account_id')
            ->leftjoin('user_violate as v', 'v.user_id', '=', 'u.id')
            ->leftjoin('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            ->where(function ($query) use ($keywords, $keywords_type) {
                if ($keywords) {
                    if ($keywords_type) {
                        switch ($keywords_type) {
                            case 1:
                                $query->where('l.account', 'like', "%$keywords%");
                                break;
                            case 2:
                                $query->where('l.username', 'like', "%$keywords%");
                                break;
                            case 3:
                                $query->where('l.id_card', 'like', "%$keywords%");
                                break;
                            case 4:
                                $query->where('l.tel', 'like', "%$keywords%");
                                break;
                            case 5:
                                $query->where('w.nickname', 'like', "%$keywords%");
                                break;
                        }
                    } else {
                        $query->where('l.username', 'like', "%$keywords%")
                            ->Orwhere('l.account', 'like', "%$keywords%")
                            ->Orwhere('l.id_card', 'like', "%$keywords%")
                            ->Orwhere('l.tel', 'like', "%$keywords%")
                            ->Orwhere('w.nickname', 'like', "%$keywords%");
                    }
                }
            })
            ->where(function ($query) use ($is_volunteer) {
                if ($is_volunteer) {
                    $query->where('l.is_volunteer', $is_volunteer);
                }
            })
            ->where(function ($query) use ($is_violate, $violate_config) {
                if ($violate_config && ($is_violate == 1 || $is_violate == 2)) {
                    if ($is_violate == 1) {
                        $symbol = '>';
                    } elseif ($is_violate == 2) {
                        $symbol = '=';
                    }
                    $sql = '';
                    foreach ($violate_config as $key => $val) {
                        if (empty($sql)) {
                            $sql = $query->where($val['field'] . '_violate_num', $symbol, 0);
                        } else {
                            if ($is_violate == 1) {
                                $sql->orWhere($val['field'] . '_violate_num', $symbol, 0);
                            } else {
                                $sql->orWhere($val['field'] . '_violate_num', $symbol, 0)->orWhere($val['field'] . '_violate_num', 'is null');
                            }
                        }
                    }
                }
            })
            ->orderByDesc($sort)
            ->paginate($limit)
            ->toArray();
        // dump(DB::getQueryLog());
        // die;
        return $res;
    }


    /**
     * 获取注册人数（绑定读者证人数）
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $type 1 注册人数  2 绑定读者证人数（弃用）
     */
    public function getUserNumber($type = 1, $start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($type, $start_time, $end_time) {
            if ($type == 2) {
                $query->whereNotNull('account_id');
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->count();
        return $number;
    }



    /**
     * 注册人数统计(折线图)
     * @param start_time  开始时间
     * @param end_time  结束时间
     * @param node  方式  1 年  2 月   3 日  如果为空，则根据实际来
     */
    public function registerStatistics($start_time = null, $end_time = null, $node = null)
    {
        if ($node == 3 || (empty($node) && date('Y-m-d', strtotime($start_time)) == date('Y-m-d', strtotime($end_time)))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("count(id) as number")];
        } elseif ($node == 2 || (empty($node) && date('Y-m', strtotime($start_time)) == date('Y-m', strtotime($end_time)))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("count(id) as number")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m') as times"), DB::raw("count(id) as number")];
        }

        $res = $this->select($field)->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->orderBy('times')
            ->groupBy('times')
            ->get()
            ->toArray();
        return $res;
    }
    /**
     * 获取用户id
     * @param wechat_id
     * @param account_id
     */
    public function getUserInfoByWechatAccountId($wechat_id, $account_id)
    {
        $res = $this->select('u.id', 'w.open_id', 'account_id')->from($this->getTable() . ' as u')
            ->join('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            ->where(function ($query) use ($wechat_id, $account_id) {
                if ($wechat_id) {
                    $wechat_id_arr = is_array($wechat_id) ? $wechat_id : explode(',', $wechat_id);
                    $query->whereIn('wechat_id', $wechat_id_arr);
                }
                if ($account_id) {
                    $account_id_arr = is_array($account_id) ? $account_id : explode(',', $account_id);
                    $query->whereIn('account_id', $account_id_arr);
                }
            })->get()
            ->toArray();
        return $res;
    }


    /**
     * 访问人数
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     */
    public function getRegisterNumber($start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->count('id');
        return $number;
    }
    /**
     * 邀请用户列表
     * @param limit 限制条数 默认为 10
     * @param user_id 用户 id
     */
    public function inviteUserList($user_id, $limit = 10)
    {
        $res = $this->from('user_info as u')
            ->select(['u.id as user_id', 'w.nickname', 'w.head_img', 'w.create_time', 'l.account'])
            ->leftjoin('user_account_lib as l', 'l.id', '=', 'u.account_id')
            ->leftjoin('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            ->where('u.invite_user_id', $user_id)
            ->orderByDesc('u.create_time')
            ->paginate($limit)
            ->toArray();
        return $res;
    }

    /**
     * 用户统计
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(类型标签)
     * @param sort 排序方式   1 默认排序（默认）  2 积分倒序  3 报名活动场次  4 征集活动场次  5 完成任务数
     */
    public function userStatistics($keywords, $sort, $page, $limit)
    {
        if ($sort == 2) {
            $sort_field = 'score';
            $first_limit = $limit;
            $first_page = $page;
        } elseif ($sort == 1) {
            $sort_field = 'create_time';
            $first_limit = $limit;
            $first_page = $page;
        } else {
            $sort_field = 'create_time';
            $first_limit = 99999;
            $first_page = 1;
        }

        $field = [
            'u.id',
            'u.id as user_id',
            'l.account',
            'l.username',
            'l.score',
            'u.create_time',
            'w.nickname',
            'w.head_img'
        ];
        //    DB::enableQueryLog();
        $res = $this->from('user_info as u')
            ->select($field)
            ->leftjoin('user_account_lib as l', 'l.id', '=', 'u.account_id')
            ->leftjoin('user_violate as v', 'v.user_id', '=', 'u.id')
            ->leftjoin('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('l.username', 'like', "%$keywords%")
                        ->Orwhere('l.account', 'like', "%$keywords%")
                        ->Orwhere('w.nickname', 'like', "%$keywords%");
                }
            })
            ->orderByDesc($sort_field)
            ->paginate($first_limit, ['*'], 'page', $first_page) //手动传分页参数
            ->toArray();
        //  dump(DB::getQueryLog());
        //  die;

        $activityApplyModel = new ActivityApply();
        $competiteActivityWorksModel = new CompetiteActivityWorks();
        $readingTaskExecuteModel = new ReadingTaskExecute();
        if (in_array($sort, [3, 4, 5])) {
            foreach ($res['data'] as $key => $val) {
                if ($sort == 3) {
                    $res['data'][$key]['activty_number'] = $activityApplyModel->getUserApplyNumber($val['id']);
                    $sort_field = 'activty_number';
                } elseif ($sort == 4) {
                    $res['data'][$key]['competite_activty_number'] = $competiteActivityWorksModel->getUserApplyNumber($val['id']);
                    $sort_field = 'competite_activty_number';
                } else {
                    $res['data'][$key]['reading_task_number'] = $readingTaskExecuteModel->userReadingTaskProgress(null, $val['id']);
                    $sort_field = 'reading_task_number';
                }
            }

            $res['data'] = sort_arr_by_one_field($res['data'], $sort_field, [SORT_NUMERIC, SORT_DESC]);
            $res['data'] = array_slice($res['data'], ($page - 1) * $limit, $limit); //自己排序
        }

        foreach ($res['data'] as $key => $val) {
            if ($sort != 3) {
                $res['data'][$key]['activty_number'] = $activityApplyModel->getUserApplyNumber($val['id']);
            }
            if ($sort != 4) {
                $res['data'][$key]['competite_activty_number'] = $competiteActivityWorksModel->getUserApplyNumber($val['id']);
            }
            if ($sort != 5) {
                $res['data'][$key]['reading_task_number'] = $readingTaskExecuteModel->userReadingTaskProgress(null, $val['id']);
            }
        }
        return $res;
    }


    // 生成实例
    public static function getInstance()
    {
        return new self;
    }
}
